import { useState } from 'react'
import { Input, Button, Typography, Space, Tag, Radio } from 'antd'
import { PlayCircleOutlined, PauseCircleOutlined, ReloadOutlined, ThunderboltOutlined } from '@ant-design/icons'
import { motion } from 'framer-motion'
import { useBoolean, useInterval } from 'ahooks'

const { Text } = Typography

const SPEEDS = {
  normal: { value: 100, label: '正常' },
  fast: { value: 50, label: '快速' },
}

const DrinkTime = () => {
  const [players, setPlayers] = useState<string[]>([])
  const [inputValue, setInputValue] = useState('')
  const [selectedPlayer, setSelectedPlayer] = useState<string | null>(null)
  const [gridPosition, setGridPosition] = useState(4)
  const [isRunning, { setTrue, setFalse }] = useBoolean(false)
  const [speed, setSpeed] = useState<'normal' | 'fast'>('normal')

  const handleInputConfirm = () => {
    if (inputValue && !players.includes(inputValue)) {
      setPlayers([...players, inputValue])
      setInputValue('')
    }
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleInputConfirm()
    }
  }

  const handleStart = () => {
    if (players.length > 0) {
      setTrue()
    }
  }

  const getGridPlayers = () => {
    if (players.length === 0) return Array(9).fill('')
    
    const repeatedPlayers = [...players]
    while (repeatedPlayers.length < 9) {
      repeatedPlayers.push(...players)
    }
    
    const gridPlayers = repeatedPlayers.slice(0, 9)
    
    if (isRunning && selectedPlayer) {
      const positions = Array(9).fill('')
      positions[gridPosition] = selectedPlayer
      return positions
    }
    
    return gridPlayers
  }

  useInterval(
    () => {
      const randomIndex = Math.floor(Math.random() * players.length)
      setSelectedPlayer(players[randomIndex])
      setGridPosition(Math.floor(Math.random() * 9))
    },
    isRunning ? SPEEDS[speed].value : undefined
  )

  return (
    <Space direction="vertical" className="w-full" size="large" align="center">
      <Space direction="vertical" className="w-80" size="small">
        <Text>添加参与者</Text>
        <Input
          placeholder="输入名字后按回车添加"
          value={inputValue}
          onChange={e => setInputValue(e.target.value)}
          onPressEnter={handleKeyPress}
          disabled={isRunning}
        />
      </Space>

      {players.length > 0 && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center"
        >
          <Space size={[4, 8]} wrap>
            {players.map(player => (
              <Tag
                key={player}
                color="blue"
                closable={!isRunning}
                onClose={() => setPlayers(players.filter(p => p !== player))}
              >
                {player}
              </Tag>
            ))}
          </Space>
        </motion.div>
      )}

      <div className="w-80 h-80 grid grid-cols-3 gap-2 bg-gray-100 p-2 rounded-lg">
        {getGridPlayers().map((player, index) => {
          const isSelected = !isRunning && player === selectedPlayer
          const isHighlighted = isRunning ? player : isSelected

          return (
            <motion.div
              key={index}
              className={`relative flex items-center justify-center rounded-lg ${
                isHighlighted ? 'bg-blue-500 text-white' : 'bg-white'
              } ${isRunning && player ? 'shadow-lg' : ''}`}
              animate={{
                scale: isRunning && player ? 1.05 : 1,
                backgroundColor: isHighlighted ? '#1890ff' : '#ffffff'
              }}
              transition={{ duration: 0.2 }}
            >
              <Text
                className={`absolute text-xl font-bold ${isHighlighted ? 'text-white/20' : 'text-gray-300'}`}
              >
                {index + 1}
              </Text>
              {player && (
                <Text
                  className={`text-xl font-bold relative z-10 ${isHighlighted ? 'text-white' : 'text-gray-400'}`}
                  style={{ textShadow: isHighlighted ? '0 2px 4px rgba(0,0,0,0.2)' : 'none' }}
                >
                  {player}
                </Text>
              )}
            </motion.div>
          )
        })}
      </div>

      <Radio.Group
        value={speed}
        onChange={e => setSpeed(e.target.value)}
        disabled={isRunning}
        optionType="button"
        buttonStyle="solid"
      >
        <Radio.Button value="normal">
          <Space>
            <PlayCircleOutlined />
            正常
          </Space>
        </Radio.Button>
        <Radio.Button value="fast">
          <Space>
            <ThunderboltOutlined />
            快速
          </Space>
        </Radio.Button>
      </Radio.Group>

      {!isRunning && selectedPlayer && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="text-center"
        >
          <Text type="secondary" className="text-lg">
            🍺 {selectedPlayer} 该你喝了！
          </Text>
        </motion.div>
      )}

      <Space size="middle">
        <Button
          type={isRunning ? 'primary' : 'default'}
          icon={isRunning ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
          onClick={isRunning ? setFalse : handleStart}
          size="large"
          disabled={players.length === 0}
        >
          {isRunning ? '停止' : '开始'}
        </Button>
       
      </Space>
    </Space>
  )
}

export default DrinkTime 